import { useEffect, useState, useRef } from 'react';
import { ChevronDownIcon, XIcon } from 'lucide-react';
interface FilterOption {
  id: string;
  label: string;
}
interface FilterProps {
  label: string;
  options: FilterOption[];
  selectedOptions: string[];
  onChange: (selected: string[]) => void;
}
const Filter = ({
  label,
  options,
  selectedOptions,
  onChange
}: FilterProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const toggleOption = (optionId: string) => {
    if (selectedOptions.includes(optionId)) {
      onChange(selectedOptions.filter(id => id !== optionId));
    } else {
      onChange([...selectedOptions, optionId]);
    }
  };
  const handleClickOutside = (event: MouseEvent) => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
      setIsOpen(false);
    }
  };
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  return <div className="relative" ref={dropdownRef}>
      <button onClick={() => setIsOpen(!isOpen)} className="flex items-center justify-between w-full px-4 py-2 text-sm bg-[#151518] rounded-lg hover:bg-[#1a1a1d] focus:outline-none focus:ring-1 focus:ring-[#4361ee]">
        <span>{label}</span>
        <ChevronDownIcon size={16} className={`ml-2 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>
      {isOpen && <div className="absolute z-10 w-full mt-2 bg-[#151518] border border-[#4361ee]/20 rounded-lg shadow-lg py-2">
          {options.map(option => <label key={option.id} className="flex items-center px-4 py-2 text-sm cursor-pointer hover:bg-[#1a1a1d]">
              <input type="checkbox" className="mr-2 form-checkbox h-4 w-4 text-[#4361ee] rounded border-[#8a8f98] focus:ring-[#4361ee]" checked={selectedOptions.includes(option.id)} onChange={() => toggleOption(option.id)} />
              {option.label}
            </label>)}
        </div>}
      {selectedOptions.length > 0 && <div className="flex flex-wrap gap-2 mt-2">
          {selectedOptions.map(optionId => {
        const option = options.find(o => o.id === optionId);
        return option ? <div key={optionId} className="flex items-center bg-[#4361ee]/20 text-[#4361ee] text-xs px-2 py-1 rounded-full">
                {option.label}
                <button onClick={() => toggleOption(optionId)} className="ml-1 focus:outline-none">
                  <XIcon size={12} />
                </button>
              </div> : null;
      })}
        </div>}
    </div>;
};
export default Filter;